﻿using System.IO;
using System.IO.Compression;
using System.Text;

namespace Jinndev {

    public class GZipUtil {

        public static string Decompress(byte[] bytes, Encoding encoding = null) {
            if (encoding == null) {
                encoding = Encoding.UTF8;
            }
            string result = string.Empty;
            using (MemoryStream ms = new MemoryStream(bytes)) {
                using (GZipStream decompressedStream = new GZipStream(ms, CompressionMode.Decompress)) {
                    using (StreamReader sr = new StreamReader(decompressedStream, encoding)) {
                        result = sr.ReadToEnd();
                    }
                }
            }
            return result;
        }

        public static byte[] Compress(byte[] rawData) {
            using (MemoryStream ms = new MemoryStream()) {
                GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true);
                compressedzipStream.Write(rawData, 0, rawData.Length);
                compressedzipStream.Close();
                return ms.ToArray();
            }
        }

        public static byte[] Compress(string str, Encoding encoding = null) {
            if (encoding == null) {
                encoding = Encoding.UTF8;
            }
            byte[] rawData = encoding.GetBytes(str);
            return Compress(rawData);
        }

        //public static string DecompressFile(string fileName) {
        //    using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
        //        using (GZipStream decompressedStream = new GZipStream(fileStream, CompressionMode.Decompress)) {
        //            StreamReader reader = new StreamReader(decompressedStream);
        //            string result = reader.ReadToEnd();//重点
        //            reader.Close();
        //            return result;
        //        }
        //    }
        //}


    }

}
